package annotationAndReflection;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.junit.Test;

import java.lang.reflect.Constructor;

/**
 * @author mubei
 * @date 2021/11/25
 * @description
 */
public class ReflectCreateInstance {

    public static void main(String[] args) throws Exception {
        // 1. 获取User类的Class对象
        Class<?> userClass = Class.forName("annotationAndReflection.User");
        //2. 通过public的无参构造器
        User user = (User)userClass.newInstance();
        System.out.println(user);
        //3.通过public有参构造器
        Constructor<?> constructor = userClass.getConstructor(String.class);
        User user1 = (User)constructor.newInstance("mubei");
        System.out.println(user1);
        //4 通过非public的有参构造器创建实例
        Constructor<?> constructor1 = userClass.getDeclaredConstructor(String.class, int.class);
        constructor1.setAccessible(true);
        User user2 =(User) constructor1.newInstance("liuzimo", 18);
        System.out.println(user2);
    }



}



@NoArgsConstructor
@Setter
@Getter
class User{
    private  String name="ah";
    private  int age=100;

    public User(String name){
        this.name = name;
    }

    private User(String name,int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}